package com.wk.springboot.mp;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author wang.k
 * @since 2024-12-18
 */
@Getter
@Setter
@Accessors(chain = true)
@TableName("test_user")
@NoArgsConstructor
public class TestUser implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String id;

    @TableField("name")
    private String name;

    private Integer version;

    public TestUser(String name,Integer version){
        this.name = name;
        this.version = version;
    }

    public static void main(String[] args) {
        // 创建一些样本数据
        List<TestUser> dataList = Arrays.asList(
                new TestUser("A", 1),
                new TestUser("B", 2),
                new TestUser("A", 3),
                new TestUser("A", null),
                new TestUser("B", null),
                new TestUser("B", 4),
                new TestUser("C", 5),
                new TestUser("D", null)
        );

        // 使用 Java 8 Stream API 进行分组和找出每个 name 的最大 version
        Map<String, Integer> maxVersionPerName = dataList.stream()
                .collect(Collectors.groupingBy(
                        TestUser::getName, // 按 name 分组
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparingInt((TestUser data) ->
                                        data.getVersion() != null ? data.getVersion() : Integer.MIN_VALUE)),
                                optionalData -> {
                                    // 如果 optionalData 是空，则表示没有 version，默认设置为 1
                                    Integer maxVersion = optionalData
                                            .map(TestUser::getVersion)
                                            .orElse(0); // 如果最大版本是 null，默认为 0
                                    return maxVersion == 0 ? 1 : maxVersion + 1; // 如果是 0，设为 1，其他加 1
                                })
                ));

        // 输出结果
        maxVersionPerName.forEach((name, maxVersion) ->
                System.out.println("Name: " + name + ", Max Version: " + maxVersion)
        );
    }
}
